<template>
  <div>
    <a-modal v-model:visible="visible" :width="950" title="新增备忘录"
             @cancel="cacelModel" :bodyStyle="bodyStyle"  @ok="handleOk">
      <a-form :model="formState" ref="formAdd"
              labelAlign="left"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
      >
      <a-row :gutter="16">
        <a-col :span="7" :style="{paddingBottom: '10px'}">
          <div class="custom-drag">
            <div>
              <a-form-item name="dragger" no-style>
                <a-upload-dragger v-model:fileList="fileList"
                                  :max-count="1"
                                  :beforeUpload="beforeUpload"
                                  @change="postFile"
                                  :customRequest="customRequest"
                                  :style="{border: 0}"
                                  @remove="fileRemove"
                                  name="file"
                                  accept=".pdf">
                  <div class="dragger-img">
                    <img src="@/assets/images/ResourceContract/file.png" alt="">
                  </div>
                  <p class="ant-upload-text" :style="{color: '#2C3749'}">将文件拖到此处，或 <span :style="{color: '#0062AD'}">点击上传</span> </p>
                  <p class="ant-upload-hint" :style="{color: '#6B7A8B', fontSize: '14px'}" >只支持pdf格式</p>
                </a-upload-dragger>
              </a-form-item>
            </div>
          </div>
        </a-col>
        <a-col :span="17">
          <a-spin :spinning="spinning" tip="文件正在识别中...">
          <div class="form-item-border">
            <a-form-item label="关联主合同" name="mainContract">
              <a-select :bordered="false"
                        :fieldNames="{
                          label: 'contractName',
                          value: 'id'
                         }"
                        v-model:value="formState.mainContract"
                        placeholder="请选择关联主合同"
                        :options="allMainData" />
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="贸易模式" name="tradeModel" :rules="[{ required: true, message: '请选择贸易模式' }]">
              <a-select :bordered="false" @change="changeModel" v-model:value="formState.tradeModel" placeholder="请选择贸易模式" :options="modelAreas" />
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="贸易类型" name="tradeType" :rules="[{ required: true, message: '请选择贸易类型' }]">
              <a-select :bordered="false" v-model:value="formState.tradeType" placeholder="请选择贸易类型" :options="areas" />
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="贸易主体" name="tradeBody" :rules="[{ required: true, message: '请选择贸易主体' }]">
              <a-select :bordered="false" v-model:value="formState.tradeBody" placeholder="请选择贸易主体" :options="tradeareas" />
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="合同签订日期" name="signingDate" :rules="[{ type: 'string', required: true, message: '请输入合同签订日期' }]">
              <a-date-picker :locale="locale" :bordered="false" :style="{width: '100%'}" v-model:value="formState['signingDate']"  value-format="YYYY-MM-DD" />
            </a-form-item>
          </div>
            <div class="form-item-border" >
            <a-form-item label="买方" name="buyer" :rules="[{ required: true, message: '请输入买方' }]">
              <a-input :bordered="false" v-model:value="formState.buyer" placeholder="请输入买方"/>
            </a-form-item>
            </div>
          <div class="form-item-border">
            <a-form-item label="卖方" name="seller" :rules="[{ required: true, message: '请输入卖方' }]">
              <a-input :bordered="false" v-model:value="formState.seller" placeholder="请输入卖方"/>
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="交货方式" name="deliveryType" :rules="[{ required: true, message: '请选择交货方式' }]">
              <a-select :bordered="false" v-model:value="formState.deliveryType" placeholder="请选择交货方式" :options="wayareas" />
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="装载港" name="loadingPort" :rules="[{ required: true, message: '请输入装载港' }]">
              <a-input :bordered="false" v-model:value="formState.loadingPort" placeholder="请输入装载港"/>
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="卸载港" name="unloadingPort" :rules="[{ required: true, message: '请输入卸载港' }]">
              <a-input :bordered="false" v-model:value="formState.unloadingPort" placeholder="请输入卸载港"/>
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="交付窗口" name="deliveryWindows" :rules="[{type: 'array', required: true, message: '请选择交付窗口' }]">
              <a-range-picker :style="{width: '100%'}" :locale="locale" :bordered="false" v-model:value="formState['deliveryWindows']"  :show-time="{ format: 'HH:mm' }" value-format="YYYY-MM-DD HH:mm" />
            </a-form-item>
          </div>
          <div class="form-item-flex">
            <div class="form-item-border">
              <a-form-item label="装/卸载量" :labelCol="{span: 8}" name="loadingOrUnloadingCapacity" :rules="[{ required: true, message: '请输入合同装/卸载量' }]">
                <a-input-number :bordered="false" v-model:value="formState.loadingOrUnloadingCapacity" :style="{width: '100%'}" placeholder="请输入"  :min="1" >
                  <template #addonAfter>
                    <a-select  style="width: 100px" v-model:value="formState.unit">
                      <a-select-option :value="1">MMBtu</a-select-option>
                      <a-select-option :value="2">m³</a-select-option>
                      <a-select-option :value="3">MT</a-select-option>
                    </a-select>
                  </template>
                </a-input-number>
              </a-form-item>
            </div>
            <div class="form-item-border" :style="{padding: 0}">
              <a-form-item name="Capacity1" :rules="[{ required: true, message: '请输入' }]">
                <a-input :style="{width: '30px', padding: 0, textAlign: 'center', fontSize: '20px'}"  disabled  :bordered="false" v-model:value="formState.Capacity1"></a-input>
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item name="upFloatValue" :rules="[{ required: true, message: '请输入上浮值' }]">
                <a-input-number :style="{width: '103px'}"
                                :min="0"
                                :max="100"
                                addon-after="%"
                                :bordered="false" v-model:value="formState.upFloatValue"
                />
              </a-form-item>
            </div>
              <div class="form-item-border" :style="{padding: 0}">
                <a-form-item name="Capacity3" :rules="[{ required: true, message: '输入' }]">
                  <a-input :style="{width: '30px', padding: 0, textAlign: 'center', fontSize: '20px'}"  disabled  :bordered="false" v-model:value="formState.Capacity3"></a-input>
                </a-form-item>
              </div>
              <div class="form-item-border">
                <a-form-item name="downFloatValue" :rules="[{ required: true, message: '请输入下浮值' }]">
                  <a-input-number :style="{width: '103px'}"
                                  :min="0"
                                  :max="100"
                                  addon-after="%"
                                  :bordered="false" v-model:value="formState.downFloatValue"
                  />
                </a-form-item>
              </div>
          </div>
          </a-spin>
        </a-col>
      </a-row>
      </a-form>
      <template #footer>
        <div class="from-btn-right">
          <a-button key="back" class="border-btn"  @click="cacelModel">取消</a-button>
          <a-button key="submit" @click="handleOk" :loading="confirmLoading" class="search-btn1">保存</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import {ref, reactive, getCurrentInstance, defineEmits, onMounted} from "vue";
import axios from 'axios'
const { proxy  } = getCurrentInstance()
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import 'dayjs/locale/zh-cn';
import {BASE_URL} from "@/config/proxyIp";
import {message} from "ant-design-vue";
const visible = ref(false);
const isSubmit = ref(false)
const emit = defineEmits(['saveMemForm'])
const fileList = ref([])
const action = ref(`${BASE_URL}/con/common/uploadContractWithAnalysis`)
const bodyStyle = ref({
})
// 贸易类型
const areas = ref([
  {
    label: '长协',
    value: 1
  },
  {
    label: '中期',
    value: 2
  },
  {
    label: '现货',
    value: 3
  }
])
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
])
//交货方式
const wayareas = ref([
  {
    label: 'FOB',
    value: 1
  },
  {
    label: 'DES',
    value: 2
  },
])
const areas2 = ref([
  {
    label: '+',
    value: '+'
  },
  {
    label: '-',
    value: '-'
  },
  {
    label: '±',
    value: '±'
  }
])
const modelAreas = ref([
  {
    label: '采购',
    value: 1
  },
  {
    label: '销售',
    value: 2
  },
  {
    label: '返装销售',
    value: 3
  },
])
const labelCol = ref(
    {
      style: {
        width: '100px'
      },
    },
)

const wrapperCol = ref({
  span: 20
})
const formState = reactive({
  tradeModel: undefined, // 贸易模式
  mainContract: undefined, //关联主合同ID
  tradeType: 3, // 贸易类型
  tradeBody: undefined, //贸易主体
  signingDate: '', // 签订日期
  buyer: '', //买方
  seller: '', // 卖方
  deliveryType: undefined, //交货方式
  loadingPort: '', //装货港口
  deliveryWindowBegin: '', // 交付窗口开始
  deliveryWindowEnd: '', // 交付窗口结束
  unloadingPort: '', // 卸载窗口
  contractPrice: '', //合同价格
  allowLoadingTime: '', //允许装载时间
  evaporationRate: '', //蒸发率
  demurrageRate: '', //滞期费率(每天)
  filePath: '', // 合同文件地址
  deliveryWindows: [], //交付窗口
  loadingOrUnloadingCapacity: '', //合同装卸载量值
  unit: 1, // 装卸载量单位
  upFloatValue: '', //上浮值
  downFloatValue: '', // 下浮值
  Capacity1: '+',
  Capacity3: '-',
  buyerTradeBody: undefined,
  sellerTradeBody: undefined
})
const formAdd = ref()
let cancelSourceList = ref([])
const showModal = () => {
  visible.value = true
  console.log('formAdd', formAdd.value)
  getAll()
};
const cacelModel = () =>{
  visible.value = false
  isSubmit.value = false
  formAdd.value.resetFields()
  fileList.value = []
  cancelSourceList.value[0].cancel()
  spinning.value = false
}
const confirmLoading = ref(false)
const handleOk = () => {
  if(formState.filePath) {
    formAdd.value.validateFields().then(() => {
      formState.deliveryWindowBegin = formState.deliveryWindows[0]
      formState.deliveryWindowEnd = formState.deliveryWindows[1]
      console.log('上传的formData', formState);
      confirmLoading.value = true;
      proxy.$api.postAddMemorandum(formState).then(res => {
        if (res.resultCode === 0) {
          visible.value = false;
          isSubmit.value = true;
          confirmLoading.value = false;
          emit('saveMemForm', isSubmit.value)
          message.success('新增备忘录成功')
          formAdd.value.resetFields()
        }
      })
    }).catch(err => {
      console.log('请输入', err)
    })
  } else {
    message.error('请上传合同原件')
  }

};
const spinning = ref(false)
const postFile = (info) => {
  console.log('上传文件1', info)
  const status = info.file.status
  if (status === 'done') {
    formState.filePath = info.file.response.resultObject.path
    console.log('上传文件返回的参数', info.file.response)
    const contractData = info.file.response.resultObject.contractData
    let contractKey = Object.keys(contractData)
    if (contractKey.length === 0) {
      message.error('识别失败，请手动输入')
    } else {
      Object.assign(formState, contractData)
    }
    spinning.value = false
    console.log('解析出来的参数', formState)
  } else if (status === 'error') {
    spinning.value = false
    message.error(`${info.file.name} 文件上传失败`);
  }
}
const beforeUpload = (file) => {
  console.log('上传文件2', file)
  let houzui = file.name.substring(file.name.lastIndexOf('.'), file.name.length).toLowerCase()
  let res = ['.pdf'].includes(houzui)
  if (!res) {
    fileList.value = []
    message.error('请上传 PDF 文件')
  }
  spinning.value = true
  return res
}
const customRequest = (options) => {
  let { file, onSuccess, onError } = options
  const CancelToken = axios.CancelToken
  const source = CancelToken.source()
  const formData = new FormData()
  formData.append('file', file )
  formData.append('contractType', 'con_resource_memorandum' )
  cancelSourceList.value.push(source)
  //importExcelFinalUrl是你的接口url
  axios.post(action.value, formData, {
    cancelToken: source.token
  }).then((res) => {
    console.log('调用成功了没', res)
    file.status = 'done'
    //这里onSuccess的第一个参数是接口响应结果，会传到change事件中去
    onSuccess(res.data, file)
  }).catch((res) => {
    file.status = 'error'
    onError(res.data, file)
  })
}
const fileRemove = () => {
  console.log('点击移除了?',  formAdd.value)
  cancelSourceList.value[0].cancel()
  spinning.value = false
  formAdd.value.resetFields()
}
/**
 * 查询所有主合同
 * */
const allMainData = ref([])
const getAll = () => {
  proxy.$api.getAllMainList().then(res => {
    console.log('所有的主合同', res)
    allMainData.value = res.resultObject
    allMainData.value.map((item) => {
      Object.assign(item, {
        id: item.id.toString()
      })
    })
  })
}
const changeModel = (val) => {
  if (Number(val) === 1) {
    formState.tradeBody = formState.buyerTradeBody
  } else {
    formState.tradeBody = formState.sellerTradeBody
  }
}
onMounted(() => {
  console.log('window.sellerTradeBodyscreen.width', window.screen.width)
  if (window.screen.width < 1920) {
    const bodyObj = {
      height: '400px',
      overflow: 'auto'
    }
    bodyStyle.value = bodyObj
  } else {
    bodyStyle.value = {}
  }
})
// eslint-disable-next-line no-undef
defineExpose({
  showModal,
  handleOk
})
</script>

<style lang="scss" scoped>
.form-item-flex {
  display: flex;
  justify-content: space-between;
  .form-item-border {
    margin-right: 4px;
  }
}
.from-btn-right {
  height: 62px;
  line-height: 62px;
  background: #ffffff;
 // box-shadow: 0px -4px 9px 0px rgba(0,0,0,0.09);
}
.dragger-img {
  margin-top: 40%;
  img {
    width: 114px;
    height: 110px;
  }
}
.umiUnit {
  width: 30px;
  height: 30px;
}
.custom-drag {
  width: 100%;
  height: 100%;
  border: 1px solid #DCDEE0;
  &:hover {
    border-color: #40a9ff;
  }
  &:active {
    border-color: #40a9ff;
  }
}
</style>
